package com.campfire.intelligentsecurity.sys.service;


import com.campfire.intelligentsecurity.sys.bean.ListPager;
import com.campfire.intelligentsecurity.sys.bean.QueryMap;

import com.campfire.intelligentsecurity.sys.bean.QueryParam;
import com.campfire.intelligentsecurity.sys.kit.PagerKit;
import com.github.drinkjava2.jsqlbox.DbContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseService {
    protected final Logger LOG = LoggerFactory.getLogger(getClass());
    @Autowired
    public HttpServletRequest request;

    @Autowired
    @Qualifier("main")
    public DbContext dbContext;

    /**
     * 自动封装list需要的结果集
     *
     * @param sql
     * @param params 第一个参数表示是否自动注入前台参数
     * @return
     */
    protected ListPager builder(String sql, Object... params) {
        QueryMap userParams = getUserParams();
        boolean auto = true;
        Object[] params_ = new Object[0];
        if (params.length != 0) {
            params_ = new Object[params.length - 1];
            if (params[0] instanceof Boolean) {
                auto = (boolean) params[0];
                for (int i = 1; i < params_.length; i++) {
                    params_[i - 1] = params[i];
                }
            } else {
                params_ = params;
            }
        }
        PagerKit pageUtil = new PagerKit(sql, auto, userParams, params_);
        ListPager pager = pageUtil.builder();
        return pager;
    }

    public QueryMap getUserParams() {
        Map<String, QueryParam> params = new HashMap<>();
        Map<String, String[]> m = request.getParameterMap();
        m.forEach((k, v) -> {
            QueryParam queryParam = new QueryParam(k, v);
            params.put(k, queryParam);
        });
        return new QueryMap(params);
    }

    public String getUUID() {
        return dbContext.qryString("select REPLACE(UUID(),'-','')");
    }
}
